package com.mobi.Survey.lib.activities;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;

import org.xml.sax.SAXException;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.widget.ListView;

import com.mobi.Survey.lib.R;
import com.mobi.Survey.lib.db.SurveyTable;
import com.mobi.Survey.lib.model.DefaultSurveyXmlParser;
import com.mobi.Survey.lib.model.SurveyPojo;
import com.mobi.Survey.lib.model.User;
import com.mobi.Survey.lib.uicomponents.SurveyCellButton;
import com.mobi.Survey.lib.utils.Device;
import com.mobi.Survey.lib.utils.Helper;

/**
 * 
 * <b>Author:</b> Yahya Arshad
 * <p>
 * <b>Company:</b> Mobi Media Soft
 * <p>
 * <b> Website:</b> www.mobimediasoft.com
 * <p>
 * SurveyListScreen.java This class is responsible for displaying survey
 */
public class SurveyListScreen extends AbstractScreen {

	private ListView lvSurveys;
	private View tvNoData;
	private View btnAutoLoadIndicator;

	private AbstractAdapterSurveyList adapter;
	public static boolean reSynch = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setTitle(User.getInstance().getLayoutName());

		// if there is no survey in database we will download default surveys
		// from remote server
		if (SurveyPojo.getTotalSurveys(this) == 0) {
			new DefaultSurveyDownloadTask().execute();
		} else {
			reSynch = true;
		}

		Device.getInstance().init(this);

		if (!Device.isSdPresentForReadWrite()
				&& !Helper.createDirIfNotExists(Helper.APP_FOLDER)) {
			showAlert(Messages.DIR_CREATE_ERROR);
		}

		// Set Header View background
		showHeaderImage(User.getInstance().getListImage());

		// if (User.getInstance().isShowAds() &&
		// Helper.isNetworkAvailable(getBaseContext()) && adsEnabled) {}
		String userId = null;
		
		boolean match = true;
		if(getIntent().getExtras()==null){
			match = true;
		}else{
			userId = getIntent().getExtras().getString("user_id");
			if(null != userId){
				match = userId.equalsIgnoreCase(getAutoLoadUserId(this));
			}else{
				match = true;
			}
		}
		
		

		if (isAutoLoadId(this) && match) {
			btnAutoLoadIndicator.setVisibility(View.VISIBLE);
			btnAutoLoadIndicator.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View v) {
					if (isAutoLoadId(v.getContext())) {
						// setAutoLoad(false, v.getContext());

						startMapActivity();

						finish();

					}
				}
			});

		} else {
			btnAutoLoadIndicator.setVisibility(View.GONE);
		}

	}

	private void startMapActivity() {
		String stringClassname = getPackageName() + ".MapTabHost";
		Class<?> c = null;
		if (stringClassname != null) {
			try {
				c = Class.forName(stringClassname);
			} catch (ClassNotFoundException e) {

				e.printStackTrace();
			}
		}
		Intent intent = new Intent(SurveyListScreen.this, c);
		startActivity(intent);
	}

	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if (v instanceof SurveyCellButton) {
			final SurveyCellButton cell = (SurveyCellButton) v;
			if (null != cell.getSurveyForButton().getSubscription()
					&& !cell.getSurveyForButton().getSubscription().isNull()) {
				final Intent i = new Intent(this, SurveyInformation.class);
				i.putExtra("data", cell.getSurveyForButton().getId());
				if (null != cell.getSurveyForButton().getTxtButtonInformation()) {
					menu.add(getString(R.string.Information)).setIntent(i);
					// menu.add(
					// cell.getSurveyForButton().getTxtButtonInformation()
					// .trim()).setIntent(i);

				} else {
					menu.add(getString(R.string.Information)).setIntent(i);
				}

			}
			if (cell.getSurveyForButton().isAnswered()
					&& null != cell.getSurveyForButton()
							.getTxtBtnCorrectAnswer()) {
				Intent i = new Intent(this, SurveyAnswersScreen.class);
				i.putExtra("data", cell.getSurveyForButton().getId());
				menu.add(cell.getSurveyForButton().getTxtBtnCorrectAnswer())
						.setIntent(i);
			}

			if (null != cell.getSurveyForButton().getTxtBtnSurveyResult()) {
				Intent i = new Intent(this, AggregateResultScreen.class);
				i.putExtra("data", cell.getSurveyForButton().getId());
				menu.add(cell.getSurveyForButton().getTxtBtnSurveyResult())
						.setIntent(i);
			}

			if (null != cell.getSurveyForButton().getTxtButtonTimer()) {
				Intent i = new Intent(this, TimerListScreen.class);

				i.putExtra("data", cell.getSurveyForButton().getId());

				menu.add(cell.getSurveyForButton().getTxtButtonTimer())
						.setIntent(i);
			}
			super.onCreateContextMenu(menu, v, menuInfo);
		}

	}

	@Override
	protected void onStart() {

		super.onStart();

	}

	@Override
	protected void onResume() {

		super.onResume();

		Helper.createDirIfNotExists(Helper.APP_FOLDER);

		if (reSynch) {
			new LoadSurveyFromDB().execute();

			reSynch = false;
		}

	}

	@Override
	public void onLowMemory() {

		Log.e("ReadyMadeMobileApp", "Exiting Due To Low Memory");
		super.onLowMemory();

		System.exit(0);
	}

	private class LoadSurveyFromDB extends AsyncTask<Integer, Integer, Integer> {
		ProgressDialog progressDialog = null;

		@Override
		protected void onPreExecute() {

			super.onPreExecute();
			try {
				progressDialog = ProgressDialog.show(SurveyListScreen.this, "",
						Messages.FETCHING_SURVEY);
				lvSurveys.setAdapter(null);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		protected void onPostExecute(Integer result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);

			if (adapter.getCount() == 0) {
				tvNoData.setVisibility(View.VISIBLE);
			} else {
				tvNoData.setVisibility(View.GONE);
				lvSurveys.setAdapter(adapter);
			}

			progressDialog.dismiss();

		}

		@Override
		protected Integer doInBackground(Integer... arg0) {
			SurveyTable surveyTable = new SurveyTable(SurveyListScreen.this);

			adapter.dispose();

			adapter.setData(surveyTable
					.getSurveysWithSubscriptions(SurveyListScreen.this));

			adapter.notifyDataSetChanged();

			surveyTable.closeDB();
			return null;
		}
	}

	@Override
	protected void onStop() {

		super.onStop();

	}

	@Override
	protected void initUiVars() {
		lvSurveys = (ListView) findViewById(R.id.lvSurveys);
		tvNoData = findViewById(R.id.tvNoData);
		// Added to support ads banner

		// Image header added now user logins WS will return Banner image and
		// its size
		headerImage = findViewById(R.id.headerImage);
		btnAutoLoadIndicator = findViewById(R.id.btnAutoLoadIndicator);
		initializeProperAdapter();

	}

	private void initializeProperAdapter() {

		int layoutId = AbstractAdapterSurveyList.getLayoutId();
		if (layoutId == LayoutIds.SURVEY_ROW_SMALL_0
				|| layoutId == LayoutIds.SURVEY_ROW_MEDIUM_1
				|| layoutId == LayoutIds.SURVEY_ROW_LARGE_2) {
			adapter = new CustomAdapterSurveys(this);
		} else if (layoutId == LayoutIds.SURVEY_ROW_SMALL_ICON_3
				|| layoutId == LayoutIds.SURVEY_ROW_MEDIUM_ICON_4
				|| layoutId == LayoutIds.SURVEY_ROW_LARGE_ICON_5) {
			adapter = new AdapterSurveyListCell(this);
		} else {
			adapter = new AdapterSurveyListCell(this);
		}

	}

	@Override
	protected int getLayoutId() {

		return LayoutIds.SURVEY_LIST;
	}

	@Override
	protected void onRelease() {
		adapter.dispose();
		adapter = null;

		lvSurveys.setAdapter(null);
		headerImage.setBackgroundDrawable(null);

		User.release();

	}

	public void onClick(final SurveyClick data) {

		if (data.getViewId() == R.id.btnSurveyInfo) {
			onBtnSurveyInfo(data.getSurvey());

		} else if (data.getViewId() == R.id.btnStartSurvey) {
			onBtnSurveyStart(data.getSurvey());

		} else if (data.getViewId() == R.id.btnSurveyResult) {
			onBtnSurveyResult(data.getSurvey());

		} else if (data.getViewId() == R.id.btnAnswer) {
			onBtnAnswer(data.getSurvey());
		} else if (data.getViewId() == R.id.btnTxtTimer) {
			onBtnSurveyTimer(data.getSurvey());
		}

	}

	private void onBtnSurveyTimer(SurveyPojo survey) {

		switchScreenTo(TimerListScreen.class, survey.getId());
	}

	private void onBtnAnswer(final SurveyPojo survey) {

		switchScreenTo(SurveyAnswersScreen.class, Long.valueOf(survey.getId()));

	}

	private void onBtnSurveyResult(final SurveyPojo survey) {

		switchScreenTo(AggregateResultScreen.class,
				Long.valueOf(survey.getId()));

	}

	private void onBtnSurveyStart(final SurveyPojo survey) {

		if (survey.isShowAllControls()) // Show all controls on single screen
			switchScreenTo(SurveyDetailAllControls.class, survey);
		else {

			switchScreenTo(SurveyDetailSingleControl.class, survey);
		}
	}

	private void onBtnSurveyInfo(final SurveyPojo sp) {

		switchScreenTo(SurveyInformation.class, Long.valueOf(sp.getId()));

	}

	/**
	 * Download default surveys from remote location
	 * 
	 * @author Yahya Arshad
	 * 
	 */
	private class DefaultSurveyDownloadTask extends
			AsyncTask<String, Object, Object> {
		private ProgressDialog progressDialog = null;
		private boolean gotSurvey = false;
		private String responseMsg = null;
		private List<SurveyPojo> surveys;

		protected Object doInBackground(String... params) {

			try {
				final DefaultSurveyXmlParser parser = new DefaultSurveyXmlParser();
				parser.parse(getResources().getString(
						R.string.default_survey_url));
				List<SurveyPojo> defSurveys = parser.getDefaultSurveys();
				if (defSurveys != null && defSurveys.size() > 0) {
					SurveyPojo.commit(SurveyListScreen.this, defSurveys);
					surveys = defSurveys;
					gotSurvey = true;

					for (final SurveyPojo survey : defSurveys) {
						final String surveyIcon = survey.getIconAddress();

						final int hash = Helper.getHashNameFromUrl(surveyIcon);
						String localPath = Helper.getTempFile(hash + "");

						if (Helper.isFileExist(localPath)) {
							Bitmap b = Helper.decode(localPath, 3);
							survey.setBitmapIcon(b);
						} else {
							survey.setBitmapIcon(null);
						}

					}

				}

			} catch (MalformedURLException e) {
				responseMsg = Messages.INVALID_URL;

			} catch (IOException e) {
				responseMsg = Messages.INVALID_HOST_INTERNET_CONNECTION;
				e.printStackTrace();

			} catch (SAXException e) {

				e.printStackTrace();
				responseMsg = Messages.INVALID_SURVEY_XML;
			} catch (RuntimeException e) {
				responseMsg = e.getMessage();
			}

			return null;
		}

		protected void onPostExecute(Object result) {

			super.onPostExecute(result);
			progressDialog.dismiss();
			progressDialog = null;
			if (gotSurvey) {
				tvNoData.setVisibility(View.GONE);
				adapter.setData(surveys);
				lvSurveys.setAdapter(adapter);

			} else {
				tvNoData.setVisibility(View.VISIBLE);
			}
			if (responseMsg != null) {
				showLongToast(responseMsg);
			}
		}

		protected void onPreExecute() {

			super.onPreExecute();
			try {
				progressDialog = ProgressDialog.show(SurveyListScreen.this, "",
						Messages.FETCHING_SURVEY);
			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}

	public void onBackPressed() {

		int id = AbstractScreen.getMapTabId(this);
		if (id > -1) {
			startMapActivity();
		}
		super.onBackPressed();
		finish();
	}
}
